<!--
 * @Author: chenli 604089679@qq.com
 * @Date: 2023-07-07 14:48:34
 * @LastEditors: chenli 604089679@qq.com
 * @LastEditTime: 2023-08-03 18:06:36
 * @FilePath: \vue3\src\views\map\index.vue
 * @Description: 地图练习
-->
<template>
  <div id="mymap" class="mymap-css">
    <MyInfoWindow
      name="自定义窗体"
      :position="position"
      v-show="showInfo"
    ></MyInfoWindow>
  </div>
  <el-image :src="imgurl"></el-image>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, watchEffect } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef } from "@vue/reactivity";
import lineData from "./mock/lineData";
import { nextTick } from "vue";
import MyInfoWindow from "./MyInfoWindow.vue";
let map = shallowRef<AMap.Map>(); //地图实例
let navg1 = null; //巡航器
let myinfoWindow = shallowRef<AMap.InfoWindow>();
let showInfo = ref(false);
let position = ref<Array<number>>([]); //巡航其位置
let imgurl = new URL('/src/assets/car1.png', import.meta.url).href
//初始化地图
function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: "3ba6501b9955bb6a531ce67035570ff4",
  };
  AMapLoader.load({
    key: "a502a10c36c57861d480ddb2c24fdeef", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    /**
     * AMap.MoveAnimation 车辆移动插件
     * misc/PathSimplifier 巡航器
     * overlay/SimpleInfoWindow 信息窗体
     */
    plugins: ["AMap.MoveAnimation"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    AMapUI: {
      plugins: ["misc/PathSimplifier", "overlay/SimpleInfoWindow"],
    },
  })
    .then((AMap) => {
      map.value = new AMap.Map("mymap", {
        //设置地图容器id
        viewMode: "2D", //是否为3D地图模式
        zoom: 6, //初始化地图级别
        center: [112.562427, 37.786068], //初始化地图中心点位置
        mapStyle: "amap://styles/dark",
      });
      map.value.on("complete", function () {
        // 地图图块加载完成后触发
        console.log("地图加载完毕");
        initAction();
      });
    })
    .catch((e) => {
      console.log(e);
    });
}

//画点
function drawPoint() {
  // 创建 AMap.Icon 实例：
  const startIcon = new AMap.Icon({
    size: new AMap.Size(40, 50), // 图标尺寸
    image: new URL("/src/assets/start.png", import.meta.url).href, // Icon的图像
    imageOffset: new AMap.Pixel(0, -60), // 图像相对展示区域的偏移量，适于雪碧图等
    imageSize: new AMap.Size(20, 25), // 根据所设置的大小拉伸或压缩图片
  });

  // // 将 Icon 实例添加到 marker 上:
  const startMarker = new AMap.Marker({
    position: new AMap.LngLat(112.900069, 36.353021),
    offset: new AMap.Pixel(-10, -10),
    icon: "/src/assets/start.png", // 添加 Icon 实例
    title: "起点",
  });

  // 创建 AMap.Icon 实例：
  const endIcon = new AMap.Icon({
    size: new AMap.Size(40, 50), // 图标尺寸
    image: "/src/assets/end.png", // Icon的图像
    imageOffset: new AMap.Pixel(0, -60), // 图像相对展示区域的偏移量，适于雪碧图等
    imageSize: new AMap.Size(20, 25), // 根据所设置的大小拉伸或压缩图片
  });
  // 将 Icon 实例添加到 marker 上:
  const endMarker = new AMap.Marker({
    position: new AMap.LngLat(113.277339, 36.324371),
    offset: new AMap.Pixel(-10, -10),
    icon: endIcon, // 添加 Icon 实例
    title: "终点",
  });
  map.value.add(startMarker);
  map.value.add(endMarker);
  // map.value.setFitView([startMarker, endMarker]);
}

//画路线
function drawLine(linePoint: number[][]) {
  //画折线得数据
  let path: AMap.LngLat[] = [];
  linePoint.forEach((item) => {
    path.push(new AMap.LngLat(item[0], item[1]));
  });
  let polyline = new AMap.Polyline({
    path: path,
    borderWeight: 1, // 轮廓宽度，默认为 1
    strokeColor: "#99FF00", // 线条颜色
    strokeWeight: 5, //线条宽度
    lineJoin: "round", // 折线拐点连接处样式
    showDir: true, //显示箭头
    geodesic: true, //大地线
    strokeStyle: "solid", //实线/虚线
  });
  map.value.add(polyline);
  // map.value.setFitView([polyline]);
}
/**
 * 移动动画  marker
 */
function moveAction() {
  // 创建 AMap.Icon 实例：
  const startIcon = new AMap.Icon({
    size: new AMap.Size(40, 50), // 图标尺寸
    image: "/src/assets/car.svg", // Icon的图像
    imageOffset: new AMap.Pixel(0, -60), // 图像相对展示区域的偏移量，适于雪碧图等
    imageSize: new AMap.Size(20, 25), // 根据所设置的大小拉伸或压缩图片
  });

  // // 将 Icon 实例添加到 marker 上:
  const moveMarker = new AMap.Marker({
    position: new AMap.LngLat(112.900069, 36.353021),
    offset: new AMap.Pixel(-10, -10),
    icon: '/src/assets/car.svg', // 添加 Icon 实例
    title: "晋AE3B76",
  });
  let path: AMap.LngLat[] = [];
  lineData.monitor.forEach((item) => {
    path.push(new AMap.LngLat(item[0], item[1]));
  });
  map.value.add(moveMarker);
  map.value.setFitView()
  moveMarker.moveAlong(path, {
    duration: 100,
  });
  
  // setTimeout(() => {
  //   console.log('-----------');
  //   moveMarker.moveAlong(path, {
  //     duration: 1000,
  //   });
  // }, 5000);
}
/**
 * 巡航器轨迹回放
 */
function moveAction2() {
  let path: AMap.LngLat[] = [];
  lineData.monitor.forEach((item) => {
    path.push(new AMap.LngLat(item[0], item[1]));
  });

  let pathSimplifierIns = new window.AMapUI.PathSimplifier({
    zIndex: 100,
    autoSetFitView: true,
    map: map.value, //所属的地图实例
    data: [
      {
        path: lineData.monitor,
      },
    ],
    getPath: function (pathData, pathIndex) {
      return pathData.path;
    },
    getHoverTitle: function (pathData, pathIndex, pointIndex) {
      return null;
    },
    clickToSelectPath: false,
  });

  //设置数据
  // pathSimplifierIns.setData([
  //   {
  //     name: "路线0",
  //     path: lineData.monitor,
  //   },
  // ]);

  navg1 = pathSimplifierIns.createPathNavigator(0, {
    loop: false, //循环
    speed: 10000,
    pathNavigatorStyle: {
      width: 24,
      height: 24,
      //使用图片
      content: window.AMapUI.PathSimplifier.Render.Canvas.getImageContent(
        "/src/assets/car.svg",
        onload,
        onerror
      ),
      strokeStyle: null,
      fillStyle: null,
      //经过路径的样式
      pathLinePassedStyle: {
        lineWidth: 6,
        strokeStyle: "green",
        // dirArrowStyle: {
        //   stepSpace: 15,
        //   strokeStyle: "white",
        // },
      },
    },
  });
  navg1.on("move", (e: any) => {
    const lngLatObj = e.target.getPosition();
    const lnglatLike = [lngLatObj.lng, lngLatObj.lat] as [number, number];
    position.value = lnglatLike;
    if (myinfoWindow.value && myinfoWindow.value.getIsOpen()) {
      myinfoWindow.value.open(map.value!, lnglatLike);
    } else {
      infoWindow();
    }
  });
  pathSimplifierIns.on("pointClick", function (e: any, info: any) {
    const { pointIndex } = info;
    if (navg1._naviStatus === "pause") {
      navg1.start();
    }
    navg1.moveToPoint(pointIndex);
  });
  map.value.setFitView();
  setTimeout(() => {
    navg1.start();
  }, 3000);
}
let isLock = false;
function limit() {
  if (isLock) {
    return;
  }
  isLock = true;
  setTimeout(() => {
    isLock = false;
    map.value.setFitView();
  }, 3000);
}
/**
 * 信息窗体
 */
function infoWindow() {
  //构建信息窗体中显示的内容
  myinfoWindow.value = new AMap.InfoWindow({
    content: document.getElementById("myInfoWindow")!,
    offset: new AMap.Pixel(0, -20),
    isCustom: true,
    autoMove: true,
  });
  myinfoWindow.value.open(map.value, [
    lineData.monitor[0][0],
    lineData.monitor[0][1],
  ]);
  showInfo.value = true;
  // limit();
}
function initAction() {
  drawPoint();
  drawLine(lineData.monitor);
  moveAction();
  // moveAction2();
}
//初始化页面数据
initMap();
</script>

<style scoped>
.mymap-css{
  width: 100%;
  height: 100vh;
}
</style>
